from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView

from rest_framework.response import Response
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ
from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializer
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework_jwt.settings import api_settings

# from rest_framework.settings import api_settings

# Create your views here.


# 构建跳转链接 引导用户进入qq登陆页面
class QQLoginURLView(APIView):

    def get(self,request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'     # 默认值

        # 1 生成QQ对象  redirect_uri 跳转页面 state 状态值
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.
                     QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        #2 调生成url的方法
        login_url = qq.get_qq_url()

        # 3 返回url
        return Response({'login_url':login_url})

#  获取openid
class OauthView(CreateAPIView):


    def get(self,request):
        # 1 获取前端传递的code
        code = request.query_params.get('code')
        if code is None:
            return Response({'errors':'缺少code值'},status=400)

        # 2 通过code值请求qq服务器获取access_token值
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,state='/')
        access_token = qq.get_access_token(code)

        # 3 通过access_token值请求qq服务器获取openid值
        openid = qq.get_open_id(access_token)

        # 4 判断openid和美多用户是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 5 未绑定 绑定openid
            # 需要加密 判断解密时间是否超过300m
            tjs = TJS(settings.SECRET_KEY, 300)
            # 加密对象
            data = tjs.dumps({'openid': openid}).decode()

            return Response({'access_token': data})

            # 6 如果绑定过则登陆成功
        else:
            # 获取用户对象
            user = qq_user.user

            # 生成jwt token

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token':token,
                'username':user.username,
                'user_id':user.id
            })
    serializer_class = OauthSerializer  # 指定序列化器








